﻿using System;
using Autofac;
using ComputerVision.BaseForm;
using ComputerVision.Common;
using ComputerVision.Data;
using ComputerVision.Services;
using ComputerVision.Services.User;
using QuanLyThongTinCoSo.Common;

namespace ComputerVision.CapPheDuyetForm
{
    public partial class frmCapPheDuyetDetail : frmDetail
    {
        private readonly IService<CapPheDuyet> _capPheDuyetService;

        public frmCapPheDuyetDetail()
        {
            InitializeComponent();
            _capPheDuyetService = Program.Container.Resolve<IService<CapPheDuyet>>();
            Text = @"Thêm mới Cấp phê duyệt";
            txtTen.Focus();
        }

        public frmCapPheDuyetDetail(Guid id)
        {
            InitializeComponent();
            _capPheDuyetService = Program.Container.Resolve<IService<CapPheDuyet>>();
            Text = @"Sửa Cấp phê duyệt";
            txtTen.Focus();

            _fromtype = Constants.TypeForm.Edit;
            guid = id;

            var item = _capPheDuyetService.Detail(id);
            if (item != null)
            {
                txtTen.Text = item.Ten;
            }
        }

        #region Validation

        protected override bool Validator()
        {
            bool flag = true;

            errorProvider.Dispose();

           if (string.IsNullOrEmpty(txtTen.Text))
            {
                errorProvider.SetError(txtTen, "Bạn chưa nhập Cấp phê duyệt. Xin vui lòng kiểm tra lại");
                flag = false;
            }

            return flag;
        }

        #endregion

        #region Insert
        protected override void Insert()
        {
            try
            {
                var model = new CapPheDuyet()
                {
                    Id = Guid.NewGuid(),
                    Ten = txtTen.Text,
                    Created = DateTime.Now,
                    CreatedById = Constants.CurrentUser,
                    Modified = DateTime.Now,
                    ModifiedById = Constants.CurrentUser
                };
                _capPheDuyetService.Create(model);
              
            }
            catch (Exception ex)
            {
                AlertList.Error("Lỗi phát sinh khi tạo mới dữ liệu.");
            }
        }
        #endregion

        #region Edit

        protected override void Edit()
        {
            var item = _capPheDuyetService.Detail(guid);
            if (item != null)
            {
                item.Ten = txtTen.Text;
                item.Modified = DateTime.Now;
                item.ModifiedById = Constants.CurrentUser;
                _capPheDuyetService.Update(item);
            }
        }

        #endregion
    }
}
